package cn.doitedu.zk.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

public class ContinueWatch {

    ZooKeeper zk = null;

    @Before
    public void init() throws Exception {
        zk = new ZooKeeper("spark01:2181,spark02:2181,spark03:2181", 2000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

                if (event.getType() == Event.EventType.NodeDataChanged) {
                    try {

                        // 处理事件
                        System.out.println("对事件做了处理......" + event.getPath() + "  " + event.getType());

                        // 重新注册监听
                        zk.getData("/abc", true, null);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    /**
     * 持续注册监听
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void continuousWatch() throws KeeperException, InterruptedException {

        zk.getData("/abc",true, null);

        Thread.sleep(Long.MAX_VALUE);

    }


}
